package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.component.WebSocketComponent;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketComponent webSocketComponent;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;


    //todo 需要校验用户的地址是否超出范围
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //地址为空
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();

        //购物车为空
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.listUserShoppingCart(shoppingCart);
        if(shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //往orders表插入订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        //address信息
        order.setAddress(address.getDetail());
        order.setPhone(address.getPhone());
        order.setConsignee(address.getConsignee());
        //number、userId
        order.setUserId(BaseContext.getCurrentId());
        order.setNumber(userId.toString()+"_"+String.valueOf(System.currentTimeMillis()));
        //状态、时间
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        log.info("insert order, number : {}", order.getNumber());
        orderMapper.insert(order);


        //往order_detail表插入详细数据
        List<OrderDetail>details=new ArrayList<OrderDetail>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            details.add(orderDetail);
        }
        log.info("insert order detail, detail len: {}", details.size());
        orderDetailMapper.insertBatch(details);


        log.info("clean user shopping cart, userId: {}", userId);
        //将用户的购物车数据清空
        shoppingCartMapper.cleanUserShoppingCart(userId);


        //返回OrderSubmitVO对象
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }


    //todo 当前直接将支付功能直接移植到本地中，后续可以将其放到服务器中
    @Override
    public OrderPaymentVO paymentPreprocess(OrdersPaymentDTO ordersPaymentDTO) {
        log.info("payment preprocess: do something");

        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(BaseContext.getCurrentId());
//        调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;

    }

    //todo: 更新今天的金额
    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.updateById(orders);

        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);
        webSocketComponent.sendToAllClient(JSON.toJSONString(map));

        //更新    "report:turnover:today_amount:"
        String endKey="report:turnover:today_amount:"+ LocalDate.now();
        Double amount = ordersDB.getAmount().doubleValue();
        redisTemplate.opsForValue().increment(endKey, amount);

    }


    @Override
    public PageResult pageQueryOrdersForUser(Integer pageNum, Integer pageSize, Integer status) {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(pageNum,pageSize);
        Page<Orders>page=orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList=new ArrayList<>();
        if(page!=null&&page.getTotal()>0){
            for (Orders orders : page) {
                List<OrderDetail> details = orderDetailMapper.getByOrderId(orders.getId());

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(details);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),orderVOList);

    }

    @Override
    public OrderVO getOrderWithDetail(Long id) {
        Orders order=orderMapper.getById(id);
        List<OrderDetail> details= orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(details);
        return orderVO;
    }

    @Override
    public void userCancelOrderById(Long id) {
        Orders order = orderMapper.getById(id);
        //订单不存在
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态: 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //接单后不可取消
        if(order.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单，无需修改所有字段，所以定义
        Orders newOrders = new Orders();
        newOrders.setId(order.getId());
        //处于待接单状态，需要腿狂
        if(order.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //todo 没有真正实现退款
            log.info("need to refund, order: {}", newOrders);
            //do something
            refundHelp(order.getAmount().doubleValue());
            newOrders.setPayStatus(Orders.REFUND);
        }

        newOrders.setStatus(Orders.CANCELLED);
        newOrders.setCancelReason("用户取消");
        newOrders.setCancelTime(LocalDateTime.now());

        orderMapper.updateById(newOrders);

    }

    void refundHelp(Double amount){
        //更新    "report:turnover:today_amount:"
        String endKey="report:turnover:today_amount:"+ LocalDate.now();
        redisTemplate.opsForValue().increment(endKey, -amount);
    }

    @Override
    public void repetition(Long id) {
        //查询该订单的订单详情
        List<OrderDetail> details = orderDetailMapper.getByOrderId(id);
        if(details==null||details.size()==0){
            throw new OrderBusinessException(MessageConstant.NO_ORDER_DETAIL);
        }

        //details转为shopping cart
        Long userId=BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = details.stream().map(detail -> {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(detail, cart, "id");
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
            return cart;
        }).collect(Collectors.toList());

        //将details添加到购物车中
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    //todo 可以使用消息队列，但需要修改前端
    // 消息队列这个方法有待验证，似乎不合理，因为后端都在同一个项目中
    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getById(id);
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());
        webSocketComponent.sendToAllClient(JSON.toJSONString(map));

    }

    @Override
    public PageResult conditionPageSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);

        //这里需要返回 OrderVo
        //订单菜品信息 orderDishes;
        //订单详情 orderDetailList;
        List<OrderVO> orderVOList=new ArrayList<>();
        if(orders!=null&&orders.getTotal()>0){
            for (Orders order : orders) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDishes(getOrderDetailStr(order));
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(orderVOList.size(),orderVOList);
    }

    private String getOrderDetailStr(Orders orders){
        List<OrderDetail> details = orderDetailMapper.getByOrderId(orders.getId());
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String>stringList=details.stream().map(detail->{
            return detail.getName() + "*" + detail.getNumber() + ";";
        }).collect(Collectors.toList());

        return String.join("",stringList);
    }

    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed=orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        //待派送数量
        Integer confirmed=orderMapper.countByStatus(Orders.CONFIRMED);

        //派送中数量
        Integer deliveryInProgress=orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        return new OrderStatisticsVO(toBeConfirmed,confirmed,deliveryInProgress);

    }


    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);
    }

    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //仅有订单是待接单的状态才可以拒单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!Objects.equals(orders.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //如果用户已经付款，需要退款
        if(Objects.equals(orders.getPayStatus(), Orders.PAID)){
            log.info("need to refund ,order: {},user: {}",orders.getId(),BaseContext.getCurrentId());
            //do something
            refundHelp(orders.getAmount().doubleValue());
        }
        Orders orders1=Orders.builder()
                .id(orders.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now()).build();
        orderMapper.updateById(orders1);
    }

    public void completeOrder(Long id) {
        //仅有派送中的才能点击完成
        Orders orders = orderMapper.getById(id);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!Objects.equals(orders.getStatus(), Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders build = Orders.builder()
                .id(orders.getId())
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now()).build();
        orderMapper.updateById(build);
    }

    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //用户如果已经付款，则需要退款
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getPayStatus().equals(Orders.PAID)){
            log.info("need to refund ,order: {},user: {}",orders.getId(),BaseContext.getCurrentId());
            //do something
            refundHelp(orders.getAmount().doubleValue());
        }
        Orders build = Orders.builder()
                .id(orders.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now()).build();
        orderMapper.updateById(build);
    }

    public void deliveryOrder(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders build = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.updateById(build);
    }
}
